/**
 * layui自定义扩展
 */

window.rootPath = (function(src) {
	src = document.scripts[document.scripts.length - 1].src;
	return src.substring(0, src.lastIndexOf("/") + 1);
})();

window.varType = function(a) {
	return Object.prototype.toString.call(a).replace(/^\[object\s+|\]$/g, '');
};

layui.config({
	base: rootPath + "lay-module/",
	version: true
}).extend({
	mAdmin: "admin/mAdmin", // admin后台扩展
	mMenu: "admin/mMenu", // admin菜单扩展
	mTab: "admin/mTab", // admin tab扩展
	mTongji: "admin/mTongji", // admin 统计扩展
	mTheme: "admin/mTheme", // admin 统计扩展

	selectN: "select/selectN", //  下拉框无线级联
	step: 'step/step', // 分步表单扩展
	treeTable: 'treeTable/treeTable', //table树形扩展
	tableSelect: 'tableSelect/tableSelect', // table选择扩展
	iconPicker: 'iconPicker/iconPicker', // fa图标选择扩展
	echarts: 'echarts/echarts', // echarts图表扩展
	echartsTheme: 'echarts/echartsTheme', // echarts图表主题扩展
	wangEditor: 'wangEditor/wangEditor', // wangEditor富文本扩展
	layarea: 'layarea/layarea', //  省市县区三级联动下拉选择器
	authtree: 'authtree/authtree' // 权限树
}).use(['jquery', 'layer', 'form'], function() {
	var $ = layui.jquery,
		layer = layui.layer,
		form = layui.form;

	var lianyiTips;
	$(document).on("mouseenter", "[tips]", function() {
		lianyiTips = layer.tips($(this).attr('tips'), $(this), {
			tips: [1, '#3595CC'],
			time: 0
		});
	});
	$(document).on("mouseleave", "[tips]", function() {
		if (lianyiTips) {
			layer.close(lianyiTips);
			lianyiTips = null;
		}
	});

	// 图片放大预览
	$(document).on("mouseenter", "img[enlarge]", function() {
		var w = $(this).width(),
			h = $(this).height(),
			enlarge = $(this).attr('enlarge');
		enlarge = isNaN(enlarge) ? 10 : parseFloat(enlarge);

		w = w * enlarge;
		h = h * enlarge;

		var img = '<img class="img_msg" src="' + $(this).attr('src') + '" width="' + w + 'px" height="' + h + '" />';
		$(this).attr('index', layer.tips(img, this, {
			time: 0,
			tips: [2, 'rgba(41, 41, 41, .5)'],
			skin: 'img-enlarge-tips',
			area: [w + 30 + 'px', h + 16 + 'px']
		}));
	});
	$(document).on("mouseleave", "img[enlarge][index]", function() {
		layer.close($(this).attr('index'));
		$(this).removeAttr('index')
	});

	// 禁用textarea换行符
	$(document).on('input propertychange', 'textarea[nowarp]', function() {
		if (/^\s+|[\r\n]+/.test($(this).val())) $(this).val($(this).val().replace(/^\s+|[\r\n]+/g, ''));
	});

	form.on('switch', function(data) {
		$(this).val(data.elem.checked ? 1 : 0);
	});

	form.on('checkbox', function(data) {
		$(this).val(data.elem.checked ? 1 : 0);
	});

	// 表单lay-verify验证
	form.verify({
		//数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
		zh: [
			/^[\u0391-\uFFE5]*$/,
			'只允许输入中文'
		], // 只能输入中文
		date: [
			/^([1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]))?$/,
			'日期格式错误！'
		],
		datetime: [
			/^([1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(2[0-3]|[0-1]\d):[0-5]\d:[0-5]\d)?$/,
			'日期 + 时间格式错误！'
		], // 2019-12-12 24:59:59
		datetime2: [
			/^([1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(2[0-3]|[0-1]\d):[0-5]\d:[0-5]\d\.\d{3})?$/,
			'日期 + 时间格式错误！'
		], //2019-12-12 24:59:59.123
		mobile: [
			/^(1(([38]\d)|(4[5-9])|(5[0-35-9])|66|(7[0-8])|(9[189]))\d{8})?$/,
			'手机号码格式错误！'
		], // 手机号码
		card: [
			/^(((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\d{4}((19\d{2}(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(19\d{2}(0[13578]|1[02])31)|(19\d{2}02(0[1-9]|1\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\d{3}(\d|X|x)?)?$/,
			'身份证号码格式错误！'
		], //身份证号码
		email2: [
			/^(\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)?$/,
			'邮箱格式错误！'
		], // 邮箱
		qq: [
			/^([1-9]\d{4,9})?$/,
			'QQ号码格式错误！'
		], // QQ号码
		money: [
			/^((0|[1-9]\d*)(\.[\d]{1,2})?)?$/,
			'价格格式错误！'
		], // 价格 12.34
		rate: [
			/^(100|(0|[1-9]\d*)(\.[\d]{1,2})?)?$/,
			'百分比格式错误！'
		], // 比率 0.00-100.00
		decimal: [
			/^((0|[1-9][0-9]*)(\.[\d]+)?)?$/,
			'仅允许输入小数！'
		], //小数
		int: [
			/^(0|[1-9]\d*)?$/,
			'仅允许输入非负整数！'
		], // 非负整数 >= 0
		int2: [
			/^([1-9]\d*)?$/,
			'仅允许输入正整数！'
		] // 正整数 >= 1
	});

	window.lianyi = {
		m: function() {
			var win = window,
				frame = win.frameElement;
			while (frame && win.parent && win.parent.frameElement) {
				win = win.parent;
				frame = win.frameElement;
			}
			var re = /^((?:[^\/]+\/)*)(([\w\-]+)\.html)?(?:\?(.+)$)?/.exec(frame ? frame.getAttribute('src') : '');

			return re ? (re[1] || '') + (re[3] || '') : '';
		},

		/**
		 * [API 获取 API 地址]
		 * @param {[string|object]} params [附加get参数]
		 * @param {[type]} parent [顶级层数]
		 */
		api: function(params, parent) {
			var url = 'api.php';

			if (/^\s*(0|[1-9]\d*)\s*$/.test(parent)) {
				for (var i = 0; i < parent; i++)
					url = '../' + url;
			}

			if (varType(params) === 'Undefined' || varType(params) === 'Null')
				params = {}
			else if (varType(params) === 'String')
				params = { c: params };

			if (varType(params) === 'Object') {
				if (!params.hasOwnProperty('m')) {
					var m = this.m();
					if (m) params.m = m;
				}
				var arr = [];
				for (var k in params) arr.push(k + '=' + params[k]);
				if (arr.length > 0) url += (url.indexOf('?') < 0 ? '?' : '&') + arr.join('&');
			}
			return url;
		},

		iframe: function(a, separator) {
			var frame = window.frameElement,
				re = /^((?:[^\/]+\/)*)(([\w\-]+)\.html)?(?:\?(.+)$)?/.exec(frame ? frame.getAttribute('src') : '');

			return (re[3] ? re[3] + (separator || '_') : '') + a + '.html';
		},

		/**
		 * [load 加载框]
		 * @param  {[string]} msg [提示文字]
		 * @return {[int]}     [layer的index]
		 */
		load: function(msg) {
			return layer.msg(msg || '加载中...', {
				icon: 16,
				time: 0,
				shade: [0.1, '#000']
			});
		},

		/**
		 * [success 成功提示框]
		 * @param  {[string]} msg [提示文字]
		 * @param  {[function]} fun   [关闭后回调事件]
		 * @return {[int]}       [layer的index]
		 */
		success: function(msg, fun) {
			return layer.msg(msg, {
				icon: 1,
				shade: [0.1, '#000'],
				scrollbar: false,
				time: 1500,
				shadeClose: true
			}, function() {
				if (typeof(fun) === 'function')
					fun();
			});
		},

		/**
		 * [fail 失败提示框]
		 * @param  {[string]} msg [提示文字]
		 * @param  {[function]} fun   [关闭后回调事件]
		 * @return {[int]}       [layer的index]
		 */
		fail: function(msg, fun) {
			return layer.msg(msg, {
				icon: 2,
				shade: [0.1, '#000'],
				scrollbar: false,
				time: 2000,
				shadeClose: true
			}, function() {
				if (typeof(fun) === 'function')
					fun();
			});
		},

		/**
		 * [post 封装网络ajax请求]
		 * @param  {[object]} options [配置选项]
		 * @param  {[fucntion]} func    [成功回调函数]
		 * @return {[type]}         [无]
		 */
		request: function(options, fun) {
			if (typeof(fun) === 'function' && !options.success)
				options.success = fun;

			var loading;
			$.ajax({
				url: options.url,
				type: options.data ? 'POST' : 'GET',
				data: options.data || {},
				dataType: options.dataType || 'json',
				cache: options.hasOwnProperty('cache') ? options.cache : false,
				beforeSend: function(xhr) {
					if (options.msg !== null && options.msg !== '') loading = lianyi.load(options.msg || '请求中...');
				},
				success: function(res) {
					var code = res.code,
						msg = res.msg,
						status = code === 0 ? 'success' : 'fail',
						fun = function() {
							if (!lianyi.jump(res) && typeof(options[status]) === 'function')
								options[status](res);
						};

					if (msg)
						lianyi[status](msg, function() {
							fun();
						});
					else fun();
				},
				error: function(xhr, textStatus, errorThrown) {
					lianyi.fail(xhr.status + '：' + xhr.statusText, function() {
						if (typeof(options.error) === 'function') options.error();
					});
				},
				complete: function() {
					if (loading) layer.close(loading);
					if (typeof(options.complete) === 'function') options.complete();
				}
			});
		},

		// 根据条件自动刷新、跳转页面
		jump: function(obj) {
			if (obj.hasOwnProperty('url')) {
				if (obj.url === true)
					location.reload();
				else
					location.href = obj.url;
			} else if (obj.hasOwnProperty('parent')) {
				if (obj.parent === true)
					parent.location.reload();
				else
					parent.location = obj.parent;
			} else if (obj.hasOwnProperty('top')) {
				if (obj.top === true)
					top.location.reload();
				else
					top.location = obj.top + (top.location.hash || '');
			} else
				return false;
		}
	}
});